#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author:heqiang

"""
app id :wx06c79109521e34d2

"""
import jieba
from jieba import analyse
import random
import re
import requests
from urllib import parse
import json, time
import datetime
import messageManage
import model
from LoggerBase import log
import traceback
from taobao.active_sendmsg import send_msg_active
from webService.weixinPay import transfers

appkey = "173aee16726d444bb1f61025dd9cef74"
sid = "36576"
pid = "mm_55844929_1958550315_110731150452"
black_list = ["oxVH76k26791MzZWe-SOaGG3mN_c"]
rid = "3114449337"


def tkl_api(tkl, username="hello", wx_id="money"):
    """
    接受商品口令，转换为淘口令并返回具体格式化内容
    """
    url = "https://api.zhetaoke.com:10001/api/open_gaoyongzhuanlian_tkl.ashx"
    tkl_urlencode = parse.quote(tkl)
    formData = "appkey=%s&sid=%s&pid=%s&tkl=%s&signurl=5&relation_id=%s" % (appkey, sid, pid, tkl_urlencode,rid)
    formData_type3 = "appkey=%s&sid=%s&pid=%s&tkl=%s&signurl=3&relation_id=%s" % (appkey, sid, pid, tkl_urlencode,rid)
    # print(formData)
    con = requests.get(url=url + "?" + formData)
    res = con.text
    print(res)
    # if con.status_code == 200 and "\"status\":200" in res:
    #     product_messages = json.loads(res)["content"][0]
    #     # 处理返利额
    #     fee = float(product_messages["tkfee3"])
    #     if fee >= 1:
    #         fee = round(fee * 0.9, 2)
    #     product_messages["tkfee3"] = str(fee)
    #     # 格式化需要的信息，
    #
    #     # 拿到 item_id
    #     con_type3 = requests.get(url=url + "?" + formData_type3)
    #     res_type3 = con_type3.text
    #     res_type3 = json.loads(res_type3)["tbk_privilege_get_response"]["result"]["data"]
    #     item_id = res_type3["item_id"].split("-")[-1]
    #     # print(item_id)
    #
    #     info_tuple = (product_messages["title"], product_messages["tkl"], product_messages["size"],
    #                   product_messages["coupon_info_money"], product_messages["quanhou_jiage"],
    #                   product_messages["tkfee3"], product_messages["tkfee3"])
    #     info = messageManage.FANLIINFO % info_tuple
    #     # 并记入数据库
    #     now_time = datetime.datetime.now()
    #     try:
    #         model.get_user_info(wx_id)
    #     except:
    #         model.add_user(username=wx_id, wx_id=wx_id)
    #     model.add_tkl_record(username, wx_id, now_time, product_messages["title"], product_messages["tkl"],
    #                          product_messages["taobao_url"], item_id, product_messages["tkfee3"])
    #     # 回复的内容
    #     return info
    # else:
    #     print("没有返利，开始搜索其他同类商品。。")
    #     info = tkl_search_other(tkl, username, wx_id)
    #     return info


def tao_id_api(tao_id):
    url = "https://api.zhetaoke.com:10001/api/open_gaoyongzhuanlian.ashx"

    formData = "appkey=%s&sid=%s&pid=%s&num_iid=%s&signurl=5" % (appkey, sid, pid, tao_id)
    # print(formData)
    con = requests.get(url=url + "?" + formData)
    res = con.text
    if con.status_code == 200 and "\"status\":200" in res:

        product_messages = json.loads(res)["content"][0]

        return product_messages
    else:
        return False


def tkl_search_other(tkl, username="hello", wx_id="money"):
    url = "https://api.zhetaoke.com:10003/api/api_quanwang.ashx"
    try:
        product_txt = re.search("「(.+)」", tkl).groups()[0]
    except:
        return "sorry,该商品没有优惠~\r\n\ue338 可以试试其他同类商品哦"
    tkl_urlencode = parse.quote(product_txt)
    formData = "appkey=%s&page=1&page_size=10&sort=new&q=%s" % (appkey, tkl_urlencode)
    # print(formData)
    con = requests.get(url=url + "?" + formData)
    res = con.text
    # print(res)
    if con.status_code == 200 and "\"status\":200" in res:
        # print(res)
        product_messages = json.loads(res)["content"]
        product_message_pre = random.choice(product_messages)
    else:
        product_txt_simple = re.sub("\w", "", product_txt)
        # print(product_txt_simple)

        fenci_text = jieba.cut(product_txt_simple)

        # 第三步：提取关键词
        try:
            word_list = jieba.analyse.extract_tags(fenci_text, topK=6, allowPOS=())
        except:
            return "sorry,该商品没有优惠~\r\n\ue338 可以试试其他同类商品哦"
        for word in word_list:
            tkl_urlencode = parse.quote(word)
            formData = "appkey=%s&page=1&page_size=10&sort=new&q=%s" % (appkey, tkl_urlencode)
            # print(formData)
            con = requests.get(url=url + "?" + formData)
            res = con.text
            if "\"status\":200" not in res:
                continue
            else:
                print("关键词搜索成功：%s" % word)
                product_messages = json.loads(res)["content"]
                product_message_pre = random.choice(product_messages)
                break
        else:
            return "sorry,该商品没有优惠~\r\n\ue338 可以试试其他同类商品哦"

    product_message = tao_id_api(product_message_pre["tao_id"])

    info_tuple = (product_message["title"], product_message["tkl"], product_message["size"],
                  product_message["coupon_info_money"], product_message["quanhou_jiage"],
                  product_message["tkfee3"], product_message["tkfee3"])
    info = messageManage.FANLIINFO % info_tuple
    # 并记入数据库
    now_time = datetime.datetime.now()
    try:
        model.get_user_info(wx_id)
    except:
        model.add_user(username=wx_id, wx_id=wx_id)
    model.add_tkl_record(username, wx_id, now_time, product_message["title"], product_message["tkl"],
                         product_message["taobao_url"], product_message["tao_id"], product_message["tkfee3"])
    # 回复的内容
    return "\ue338sorry,该商品没有优惠~\r\n\r\n但小哇智能检索到有类似返利商品,可以看看哦：\r\n " + info


def search_product(wx_id, txt):
    url = "https://api.zhetaoke.com:10003/api/api_quanwang.ashx"

    tkl_urlencode = parse.quote(txt)

    formData = "appkey=%s&page=1&page_size=10&sort=new&q=%s" % (appkey, tkl_urlencode)
    # print(formData)
    con = requests.get(url=url + "?" + formData)
    res = con.text
    # print(res)
    if con.status_code == 200 and "\"status\":200" in res:
        # print(res)
        product_messages = json.loads(res)["content"]
        random.shuffle(product_messages)
        product_message_3 = product_messages[:3]
        # print(len(product_message_3))
        for product_message_pre in product_message_3:
            try:
                product_message = tao_id_api(product_message_pre["tao_id"])

                info_tuple = (product_message["title"], product_message["tkl"], product_message["size"],
                              product_message["coupon_info_money"], product_message["quanhou_jiage"],
                              product_message["tkfee3"], product_message["tkfee3"])
                info = messageManage.FANLIINFO % info_tuple
                # print(info)
                # 并记入数据库
                now_time = datetime.datetime.now()

                model.get_user_info(wx_id)

                model.add_tkl_record(wx_id, wx_id, now_time, product_message["title"], product_message["tkl"],
                                     product_message["taobao_url"], product_message["tao_id"],
                                     product_message["tkfee3"])
                send_msg_active(msg=info, wx_id=wx_id)
            except Exception:
                log.error(traceback.format_exc(limit=3))
                continue
        return True
    else:
        return False


def order_get_day(start_time, query_type, callback, tk_status=None):
    """
    查询当天的所有订单
    start_time
    query_type: 查询时间类型，1：按照订单淘客创建时间查询，2:按照订单淘客付款时间查询，3:按照订单淘客结算时间查询
    tk_status: 淘客订单状态，12-付款，13-关闭，14-确认收货（暂时无法结算佣金），3-结算成功;不传，表示所有状态
    query_type 用 2  ，tk_status 用 12和 3
    callback : 处理订单的函数，传入必须为 tb_message
    """
    url = "https://api.zhetaoke.com:10001/api/open_dingdanchaxun2_piliang.ashx"
    if tk_status is None:
        formData = "appkey=%s&sid=%s&start_time=%s&query_type=%s&signurl=1" % (
            appkey, sid, start_time, query_type)
    else:
        formData = "appkey=%s&sid=%s&start_time=%s&query_type=%s&tk_status=%s&signurl=1" % (
            appkey, sid, start_time, query_type, tk_status)

    con = requests.get(url=url + "?" + formData)
    if con.status_code == 200:
        messages = json.loads(con.text)
        # 获取到的链接列表，每个时间段的url再去请求，获得订单数据
        for urldict in messages:
            tb_con = requests.get(url=urldict["url"])
            tb_res = json.loads(tb_con.text)
            time.sleep(1)
            try:
                if "publisher_order_dto" not in tb_res["tbk_sc_order_details_get_response"]["data"]["results"].keys():

                    continue
                else:
                    tb_message_list = tb_res["tbk_sc_order_details_get_response"]["data"]["results"][
                        "publisher_order_dto"]

                    # 处理该时间段的所有订单
                    for tb_message in tb_message_list:
                        # print(tb_message)
                        callback(tb_message)
            except Exception as e:
                log.error(e, urldict["start_time"], urldict["end_time"], urldict["url"])
    else:
        log.warning("请求错误：\n%s" % con.text)


def order_get_minute(end_time, query_type, callback, tk_status=None):
    """
        end_time
        query_type: 查询时间类型，1：按照订单淘客创建时间查询，2:按照订单淘客付款时间查询，3:按照订单淘客结算时间查询
        tk_status: 淘客订单状态，12-付款，13-关闭，14-确认收货（暂时无法结算佣金），3-结算成功;不传，表示所有状态
        query_type 用 2  ，tk_status 用 12和 3
        设置时间段为5分钟
        callback : 处理订单的函数，传入必须为 tb_message
    """
    url = "https://api.zhetaoke.com:10001/api/open_dingdanchaxun2.ashx"
    start_time = datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=5)
    if tk_status is None:
        formData = "appkey=%s&sid=%s&start_time=%s&end_time=%s&query_type=%s&signurl=1&page_size=100" % (
            appkey, sid, start_time, end_time, query_type)
    else:
        formData = "appkey=%s&sid=%s&start_time=%s&end_time=%s&query_type=%s&tk_status=%s&signurl=1&page_size=100" % (
            appkey, sid, start_time, end_time, query_type, tk_status)

    con = requests.get(url=url + "?" + formData)
    if con.status_code == 200:
        messages = json.loads(con.text)
        tb_con = requests.get(url=messages["url"])
        tb_res = json.loads(tb_con.content.decode("utf-8"))
        if "publisher_order_dto" not in tb_res["tbk_sc_order_details_get_response"]["data"]["results"].keys():

            pass
        else:
            tb_message_list = tb_res["tbk_sc_order_details_get_response"]["data"]["results"][
                "publisher_order_dto"]
            log.warning("minute check order success , start add ...")
            for tb_message in tb_message_list:
                callback(tb_message)
    else:
        log.warning("请求错误：\n%s" % con.text)


def add_order(messagedict):
    """
    处理新订单，记录item_id,trade_id,tk_paid_time,tk_earning_time,pub_share_pre_fee
    查询时间段内的tkl，关联wx_id
    flag :False 可修改wxid
    synced: False 未增加user fee
    """
    # log.warning(str(messagedict))
    tk_paid_time = datetime.datetime.strptime(messagedict["tk_paid_time"], "%Y-%m-%d %H:%M:%S")
    if "tk_earning_time" in messagedict.keys():
        tk_earning_time = datetime.datetime.strptime(messagedict["tk_earning_time"], "%Y-%m-%d %H:%M:%S")
    else:
        tk_earning_time = datetime.datetime.strptime("2200-01-01 10:00:00", "%Y-%m-%d %H:%M:%S")
    # print(messagedict)
    item_id = messagedict["item_id"].split("-")[-1]
    # 先检查前15分钟内有无，对应口令，再30，再60(model实现)
    # 对查找到的tkl count+1,
    tklinfos = model.get_tkl_record(item_id, tk_paid_time)
    # update tkl
    if tklinfos:
        wx_id = tklinfos[2]
        tklfee = round(float(messagedict["pub_share_pre_fee"]) * 0.9, 2)
    else:
        wx_id = ""
        tklfee = round(float(messagedict["pub_share_pre_fee"]) * 0.9, 2)

    tklfee = str(tklfee)

    # 发送消息函数
    def smg():
        try:
            if wx_id != "":
                send_msg_active(msg=messageManage.ORDER_ADD % (messagedict["trade_id"], tklinfos[6], tklfee),
                                wx_id=wx_id)
        except:
            log.error("发送消息失败：%s ，原因\n%s" % (messagedict["trade_id"], traceback.format_exc(limit=3)))

    # 加入数据库，如果已存在检查是否更新
    try:
        if tklfee == "0":
            log.warning("发现 0 元 fee： \n " + str(tklinfos) + "\n" + str(messagedict))
        if model.get_order(messagedict["trade_id"]) == False:
            model.add_order(item_id, messagedict["trade_id"], messagedict["tk_status"],
                            tk_paid_time, tk_earning_time,
                            messagedict["pub_share_pre_fee"], tklfee, wx_id, flag=False, synced=False,
                            trade_parent_id=messagedict["trade_parent_id"])
            if tklinfos:
                model.update_tkl_count(tklinfos[0], messagedict["trade_id"])
                log.warning("加入订单：%s ; " % messagedict["trade_id"])
                smg()
        elif model.get_order(messagedict["trade_id"]) and tklinfos:
            model.update_oder_type(messagedict["trade_id"], ordertype=messagedict["tk_status"])
            model.update_oder_wx(messagedict["trade_id"], tklfee=tklfee, wx_id=wx_id)
            log.warning("更新订单：%s ，" % (messagedict["trade_id"]))
            # smg()

    except Exception as e:
        log.error("加入订单失败：%s ，原因\n%s" % (messagedict["trade_id"], traceback.format_exc(limit=3)))
        return False

    return True


def update_order_type13(messagedict):
    """
    只将tk_status为13的订单 add order处理
    """

    if messagedict["tk_status"] == 13:
        try:
            if model.get_order(messagedict["trade_id"]):
                model.update_oder_type(messagedict["trade_id"], ordertype=messagedict["tk_status"])
                log.warning("更新订单：%s ，" % (messagedict["trade_id"]))


        except Exception as e:
            log.error("更新订单状态失败：%s ，原因\n%s" % (messagedict["trade_id"], traceback.format_exc(limit=3)))
            return False


def update_order(messagedict):
    # 处理完结订单，修改订单标识，user total fee 加 fee
    try:
        print(messagedict)
        orderinfo = model.get_order(messagedict["trade_id"])
        syncedflag = orderinfo[3]
        if syncedflag == True or messagedict["refund_tag"] == 1:
            log.warning("订单已同步或退款 单号 %s 退款:%d" % (messagedict["trade_id"], messagedict["refund_tag"]))
            model.update_oder_type(messagedict["trade_id"], "3")
            return

        tk_earning_time = datetime.datetime.strptime(messagedict["tk_earning_time"], "%Y-%m-%d %H:%M:%S")
        model.update_oder_flag(messagedict["trade_id"], tk_earning_time, flag=True, synced=True)
        model.update_oder_type(messagedict["trade_id"], "3")

        # 加上 wx_id fee
        if orderinfo[0] is not None and orderinfo[0] != "":
            log.warning("user %s add fee：%.2f" % (orderinfo[0], orderinfo[1]))
            if messagedict["total_commission_fee"] :
                total_commission_fee = round(float(messagedict["total_commission_fee"] ) * 0.9, 2)
            else:
                total_commission_fee = 0
            if total_commission_fee < orderinfo[1]:
                model.add_user_fee(wx_id=orderinfo[0], fee=total_commission_fee)
            else:
                model.add_user_fee(wx_id=orderinfo[0], fee=orderinfo[1])

    except Exception as e:
        log.error("结算订单失败：%s ，原因\n%s" % (messagedict["trade_id"], traceback.format_exc(limit=3)))
    else:
        log.warning("结算订单：%s" % messagedict["trade_id"])
        # 回复，订单已结算成功 , 返利
        try:
            send_msg_active(msg=messageManage.ORDER_DONE % (messagedict["trade_id"], orderinfo[1]), wx_id=orderinfo[0])
        except:
            pass


def check_order_once(start_time=None):
    """
    timestamp : str  2022-04-29 04:35:00
    """
    # 执行一次订单检查
    try:
        if start_time == None:
            timedate = datetime.datetime.now()
            start_time = timedate.strftime("%Y-%m-%d %H:%M:%S")

        print("start check order", start_time)
        # log.warning("检查五分钟内的订单： " + start_time)
        # query_type 为2 为付款时间；订单状态 all
        order_get_minute(start_time, query_type="2", callback=add_order)
        if re.search(r" 04:3[23456]:", start_time):
            start_time_day = datetime.datetime.strptime(start_time.split(" ")[0], "%Y-%m-%d")
            start_time_day = start_time_day - datetime.timedelta(days=1)
            start_time_day_strf = start_time_day.strftime("%Y-%m-%d")
            log.warning("开始结算当天完结订单： " + start_time_day_strf)
            # 添加遗漏的新增订单
            order_get_day(start_time_day_strf, query_type="2", callback=add_order)

            # query_type 为3 为tk结算时间，订单状态3 完成结算
            start_time_day_20 = start_time_day - datetime.timedelta(days=15)
            order_get_day(start_time_day_20, query_type="3", tk_status="3", callback=update_order)

            # 更新之前取消的订单
            for i in range(1, 7):
                time_day_13 = start_time_day - datetime.timedelta(days=i)
                time_day_13_strf = time_day_13.strftime("%Y-%m-%d")
                log.warning("开始清理13状态订单： " + str(time_day_13_strf))
                order_get_day(time_day_13_strf, query_type="2", tk_status="13", callback=update_order_type13)

            # 限制黑名单
            for black_id in black_list:
                total, nodone = query_total_fee(black_id)
                if total != 0:
                    model.reset_user_fee(wx_id=black_id)

        if re.search(r"-16 04:3[23456]:", start_time):
            # 清理半年前的订单
            log.warning("开始清理半年前完结订单和淘口令记录： " + start_time)
            start_time_day = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
            model.del_order_half_year(start_time_day)
    except Exception as e:
        log.error(traceback.format_exc(limit=3))


def bond_order(wx_id, trade_id):
    # 手动绑定订单与wx_id

    orderinfo = model.get_order(trade_id)
    if orderinfo == False:
        try:
            log.warning("开始查询父订单号：%s" % trade_id)
            message = bond_parent_id(wx_id=wx_id, parent_trade_id=trade_id)
        except:
            message = "【绑定失败】 未查询到订单 ，可能原因\ue045:\n1.发送订单号不正确 \n 2.订单还未同步到小哇（一般付款5分钟后同步，最迟24h）\n 3.该订单没有返利"
    else:
        if orderinfo[2] == True:
            message = "\ue045绑定失败，已绑定用户：%s" % orderinfo[0]
        elif orderinfo[3] == True:
            message = "\ue045绑定失败，订单已经结算： %s \n 无法更改关联用户 " % orderinfo[0]
        else:
            model.update_oder_flag(trade_id, tk_earning_time=orderinfo[4], flag=True, synced=False, wx_id=wx_id)
            log.warning("强制绑定：%s --- %s" % (trade_id,wx_id))
            message = "强制绑定成功\ue30c：\n 订单号： %s \n 微信用户：%s" % (trade_id, wx_id)
    return message


def bond_parent_id(wx_id, parent_trade_id):
    trade_ids = model.get_trade_id_by_parent(parent_trade_id)
    for trade_id in trade_ids:
        orderinfo = model.get_order(trade_id)
        if orderinfo[2] == True:
            # 已强制绑定
            continue
        elif orderinfo[3] == True:
            # 跳过 ，已结算
            continue
        model.update_oder_flag(trade_id, tk_earning_time=orderinfo[4], flag=True, synced=False, wx_id=wx_id)
    message = "强制绑定\ue30c：\n 通过父订单号： %s \n 绑定了子订单：%s\n微信用户：%s" % (
        parent_trade_id, trade_ids, wx_id)
    return message


def query_total_fee(wx_id):
    # 查询余额, 以及未结算的返利总额
    try:
        total_fee = model.get_user_info(wx_id=wx_id)[0]
        nodone_fee = model.get_user_nodone_fee(wx_id=wx_id)
        return total_fee, nodone_fee
    except:
        message = "未查询到用户"
        return message


def transfer_fee(wx_id):
    try:
        userinfo = model.get_user_info(wx_id=wx_id)
        total_fee = userinfo[0]

        def deal_h(deal_fee):
            # 处理超过100元

            for i in range(int(deal_fee) // 100):
                log.warning("提现 ： %s  ，金额：%d" % (wx_id, 100))
                message = transfers(openid=wx_id, amount=100)
                if "batch_id" not in message and "out_batch_no" not in message:
                    model.add_user_fee(wx_id=wx_id, fee=100)

            else:
                yu = deal_fee % 100
                log.warning("提现 ： %s  ，金额：%d" % (wx_id, yu))
                message = transfers(openid=wx_id, amount=yu)
                if "batch_id" not in message and "out_batch_no" not in message:
                    model.add_user_fee(wx_id=wx_id, fee=yu)

            userinfo = model.get_user_info(wx_id=wx_id)
            total_after_fee = userinfo[0]
            message = "\ue30c已根据微信转账上限 提交微信转账,  转账后余额 : %.2f。" % total_after_fee
            return message

        if total_fee <= 5:
            return "\ue045可提取金额少于5元，暂时无法提现，请继续积累哦。"

        elif 100 <= total_fee <= 200:
            model.reset_user_fee(wx_id)
            message = deal_h(total_fee)
            return message

        elif total_fee >= 200:
            new_total = round((total_fee - 200), 2)
            model.reset_user_fee(wx_id, fee=new_total)
            message = deal_h(200)
            return message
        else:
            model.reset_user_fee(wx_id)
            # 转账
            log.warning("提现 ： %s  ，金额：%d" % (wx_id, total_fee))
            message = transfers(openid=wx_id, amount=total_fee)
            if "batch_id" not in message and "out_batch_no" not in message:
                model.add_user_fee(wx_id=wx_id, fee=total_fee)
                return message

            message = "\ue30c转账成功： %.2f。请微信查收转账" % total_fee

            return message

    except Exception as e:
        log.error(traceback.format_exc(limit=3))
        message = "\ue045提现失败，请稍后再试"
        return message


"""
需要自运行的进程：
1.missionTimer()

flask需要的请求响应函数：
处理淘口令  tkl_api() 
查询  query_total_fee()
提现  transfer_fee()
绑定订单    bond_order()
帮助   
"""

if __name__ == "__main__":
    # message = transfer_fee(wx_id="oxVH76nUfMZmfasXQguoSLcGUvP4")
    # print(message)
    # kouling = tkl_api(
    #     "https://m.tb.cn/h.fnQurQZ?tk=3wBd25PXHXm「雨衣电动车长款全身防暴雨双人女男电瓶车摩托车单人2021新款雨披」点击链接直接打开")
    # print(kouling)
    #
    kouling = tkl_api(
        "【淘宝】https://m.tb.cn/h.U791ZR4?tk=n1F6dXLLV93 CZ3457 「小狗吸尘器家用强力大功率地毯手持干湿吹多用小型」点击链接直接打开 或者 淘宝搜索直接打开")
    print(kouling)

    # text = search_product(wx_id="hello", txt="自行车")

    # message = bond_order(wx_id="heiwa", trade_id="2523456001990471009")
    # print(message)

    # fee = query_total_fee("money")
    # print(fee)

    # order_get_minute(end_time="2022-03-15 17:15:00", query_type=2, callback=add_order)
    #
    # order_get_day(start_time="2022-11-26", query_type="3", tk_status="3", callback=update_order)

    # check_order_once(start_time="2022-11-27 04:33:51")

    # transfer_fee(wx_id="oxVH76sARK3kcWQMvS8Zpr0kE6gY")

    # bond_order(wx_id="hello", trade_id="2778212522276471009")

    # product_txt = re.search("「.+」", tkl).group()
    # print(product_txt)

    # send_msg_active(msg="调试", wx_id="oxVH76sARK3kcWQMvS8Zpr0kE6gY")
